import 'package:flutter/material.dart';
import 'dart:async';
import '../../models/airplane_model.dart';
import '../../widgets/joystick_control.dart';
import '../../widgets/status_panel.dart';
import '../../services/bluetooth_service.dart';
import '../bluetooth_device_screen.dart';

class ManualControlScreen extends StatefulWidget {
  final AirplaneModel model;

  const ManualControlScreen({super.key, required this.model});

  @override
  State<ManualControlScreen> createState() => _ManualControlScreenState();
}

class _ManualControlScreenState extends State<ManualControlScreen> {
  final BluetoothService _bluetoothService = BluetoothService();
  Timer? _controlTimer;
  double throttle = 0.0;
  double yaw = 0.0;
  double pitch = 0.0;
  double roll = 0.0;
  bool _isConnected = false;

  @override
  void initState() {
    super.initState();
    _setupBluetoothConnection();
    _startControlLoop();
  }

  void _setupBluetoothConnection() {
    _bluetoothService.connectionState.listen((connected) {
      setState(() {
        _isConnected = connected;
      });
      if (connected) {
        _bluetoothService.startHeartbeat();
      }
    });
  }

  void _startControlLoop() {
    _controlTimer?.cancel();
    _controlTimer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
      if (_isConnected) {
        _sendControlCommand();
      }
    });
  }

  Future<void> _sendControlCommand() async {
    await _bluetoothService.sendFlightControl(
      throttle: throttle,
      pitch: pitch,
      roll: roll,
      yaw: yaw,
    );
  }

  @override
  void dispose() {
    _controlTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('手动控制模式'),
        actions: [
          // 蓝牙连接状态和按钮
          _buildBluetoothButton(),
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: _showHelp,
          ),
        ],
      ),
      body: Column(
        children: [
          // 蓝牙连接状态栏
          Container(
            padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
            color: _isConnected ? Colors.green.withOpacity(0.1) : Colors.red.withOpacity(0.1),
            child: Row(
              children: [
                Icon(
                  Icons.bluetooth,
                  color: _isConnected ? Colors.green : Colors.red,
                ),
                const SizedBox(width: 8),
                Text(
                  _isConnected ? '已连接' : '未连接',
                  style: TextStyle(
                    color: _isConnected ? Colors.green : Colors.red,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: Row(
              children: [
                // 左侧油门控制
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Text('油门控制'),
                        const SizedBox(height: 16),
                        Expanded(
                          child: JoystickControl(
                            mode: JoystickMode.vertical,
                            onPositionChanged: (x, y) {
                              setState(() {
                                throttle = -y;
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                // 右侧方向控制
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Text('方向控制'),
                        const SizedBox(height: 16),
                        Expanded(
                          child: JoystickControl(
                            mode: JoystickMode.all,
                            onPositionChanged: (x, y) {
                              setState(() {
                                yaw = x;
                                pitch = -y;
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 控制数据显示
          Container(
            padding: const EdgeInsets.all(16.0),
            color: Theme.of(context).colorScheme.surfaceVariant,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildControlValue('油门', throttle),
                _buildControlValue('偏航', yaw),
                _buildControlValue('俯仰', pitch),
                _buildControlValue('滚转', roll),
              ],
            ),
          ),
          // 紧急停止按钮
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: ElevatedButton(
              onPressed: _isConnected ? _emergencyStop : null,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red,
                foregroundColor: Colors.white,
                minimumSize: const Size(double.infinity, 50),
              ),
              child: const Text('紧急停止'),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBluetoothButton() {
    return IconButton(
      icon: Icon(
        Icons.bluetooth,
        color: _isConnected ? Colors.green : Colors.red,
      ),
      onPressed: () async {
        if (_isConnected) {
          await _bluetoothService.disconnect();
        } else {
          await Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const BluetoothDeviceScreen(),
            ),
          );
        }
      },
    );
  }

  Widget _buildControlValue(String label, double value) {
    return Column(
      children: [
        Text(label),
        Text(
          '${(value * 100).toStringAsFixed(0)}%',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Theme.of(context).colorScheme.primary,
          ),
        ),
      ],
    );
  }

  void _showHelp() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('手动控制帮助'),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('左侧控制杆: 上下移动控制油门'),
            SizedBox(height: 8),
            Text('右侧控制杆: '),
            Text('- 上下移动控制俯仰（前后）'),
            Text('- 左右移动控制偏航（左右）'),
            SizedBox(height: 16),
            Text('紧急停止按钮将立即停止所有动作并降落飞机'),
            SizedBox(height: 8),
            Text('使用前请确保已连接蓝牙设备'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('了解'),
          ),
        ],
      ),
    );
  }

  Future<void> _emergencyStop() async {
    if (_isConnected) {
      await _bluetoothService.sendEmergencyStop();
      setState(() {
        throttle = 0.0;
        yaw = 0.0;
        pitch = 0.0;
        roll = 0.0;
      });
    }

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('紧急停止'),
        content: const Text('已启动紧急停止程序，飞机将安全降落。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确认'),
          ),
        ],
      ),
    );
  }
}
